<?php
$c = mysql_connect('localhost', 'root', '') or die("Connexion au serveur impossible");
mysql_select_db('sandbox') or die("Selection de la base de données impossible");
$type = isset($_GET['type']) ? $_GET['type'] : '';
$sql = 'SELECT * FROM extractor';
switch($type){
    case 'all':
        $sql .= ' WHERE failed = 0';
        break;
    case 'some':
        $sql .= ' WHERE Telephone = "" OR Telephone is NULL OR email = "" OR email is NULL OR internet = "" OR internet is NULL';
        $sql .= ' AND failed = 0';
        break;
    case 'email':
        $sql .= ' WHERE email = "" OR email is NULL';
        $sql .= ' AND failed = 0';
        break;
    case 'telephone':
        $sql .= ' WHERE Telephone = "" OR Telephone is NULL';
        $sql .= ' AND failed = 0';
        break;
    case 'internet':
        $sql .= ' WHERE internet = "" OR internet is NULL';
        $sql .= ' AND failed = 0';
        break;
    case 'empty':
        $sql .= ' WHERE Telephone = "" AND email = "" AND internet = ""';
        $sql .= ' AND failed = 0';
        break;
    case 'failed':
        $sql .= ' WHERE failed = 1';
        break;
}
$result = mysql_query($sql, $c) or die("Erreur : " .  mysql_error($c));
$idArray = array();
?>
<!doctype html>
<html lang="fr">
    <head>
        <meta charset="utf-8">
        <title>Extraction de données</title>
        <link type="text/css" rel="stylesheet" href="../css/bootstrap.css">
        <script type="text/javascript" src="../js/jquery-1.11.0.min.js"></script>
        <script type="text/javascript" src="../js/bootstrap.js"></script>
    </head>
    <body>
        <table class="table table-bordered table-condensed table-striped table-hover">
            <thead>
                <tr>
                    <td width="10%">ID</td>
                    <td width="20%">Nom</td>
                    <td width="10%">Telephone</td>
                    <td width="10%">Email</td>
                    <td width="10%">Site Web</td>
                    <td width="10%">Adresse</td>
                    <td width="10%">Code Postal</td>
                    <td width="10%">FFR</td>
                    <td width="10%">
                        <button class="btn btn-primary all">Extraire tous les informations</button>
                    </td>
                </tr>
            </thead>
            <tbody>
                <?php while($row = mysql_fetch_assoc($result)): ?>
                <tr id="row-<?php echo $row['id']; ?>">
                    <td>
                        <a href="#" class="failed" data-id="<?php echo $row['id']; ?>"><?php echo $row['id'] ?></a>
                    </td>
                    <td><?php echo $row['nom'] ?></td>
                    <td>
                        <span id='telephone-<?php echo $row['id'] ?>'><?php echo $row['Telephone'] ?></span>
                    </td>
                    <td>
                        <span id='email-<?php echo $row['id'] ?>'><?php echo $row['email'] ?></span>
                    </td>
                    <td>
                        <span id='internet-<?php echo $row['id'] ?>'><?php echo $row['internet'] ?></span>
                    </td>
                    <td><?php echo $row['Adresse'] ?></td>
                    <td><?php echo $row['code_postal'] ?></td>
                    <td>
                        <a href='<?php echo $row['url_formulaire'] ?>'><?php echo $row['url_formulaire'] ?></a>
                    </td>
                    <td>
                        <a id="btn-<?php echo $row['id']; ?>" class="btn btn-info extract" data-id='<?php echo $row['id'] ?>' href='<?php echo $row['url_formulaire'] ?>'>Extraction</a>
                        <div class="hide" id='content-<?php echo $row['id'] ?>'></div>
                    </td>
                </tr>
                <?php $idArray[] = $row['id']; ?>
                <?php endwhile; ?>
            </tbody>
        </table>
        
        <?php //var_dump($idArray); ?>

        <script type="text/javascript">
            $idArray = [<?php $first = true; foreach($idArray as $id){echo ((!$first) ? ',' : '') ."'$id'"; $first = false;} ?>];
            $timeOut = new Array();
            $time = 0;
            $index = 0;
            $(function(){
                // Un bouton
                $('.extract').click(function(e){
                    e.preventDefault();
                    var id = $(this).attr('data-id');
                    var href = $(this).attr('href');
                    getData(href, id, $(this));
                });
                // Tous les boutons
                $('.all').click(function(e){
                    e.preventDefault();
                    var count = $idArray.length;
                    $time = count * 10;
                    $(this).text(toTime($time) + " pour terminer");
                    for(var i = 0; i < count; i++){
                        $timeOut[i] = setTimeout(function(){
                            console.log('Index : ' + $index);
                            console.log('Value : ' + $idArray[$index]);
                            extract($idArray[$index]);
                            $index++;
                        }, i * 10 * 1000);
                    }
                });
                // echec
                $('.failed').click(function(e){
                    e.preventDefault();
                    var id = $(this).attr('data-id');
                    var $ajax = $.ajax({
                        type: 'post',
                        url : 'erase.php',
                        data: '&id=' + id
                    });
                    $ajax.done(function(result){
                        if(result.done){
                            $('#row-' + id).hide('normal');
                        }
                    });
                });
            });            
            
            function extract(id){
                var $btn = $('#btn-' + id);
                var href = $btn.attr('href');
                getData(href, id, $btn);
            }
            
            /**
             * 
             * @param {type} $object
             * @param {type} id
             * @returns {String}
             */
            function toTime(seconds){
                var h = Math.floor(seconds / 3600);
                var mn = Math.floor((seconds - (h * 3600)) / 60);
                var s = seconds - (h * 3600) - (mn * 60);
                return (h < 10 ? '0' + h : h) + ':' + (mn < 10 ? '0' + mn : mn) + ':' + (s < 10 ? '0' + s : s);
            }
            
            function getData(url, id, $obj, next){
                $obj.text("Chargement des données ...").removeClass('btn-info').addClass('btn-inverse');
                var $ajax = $.ajax({
                    type: 'post',
                    url : 'opener.php',
                    data: '&url=' + encodeURI(url)
                });
                $ajax.done(function(result){
                    $obj.text("Chargement des données ...");
                    var $content = $('<div>' + result + '</div>');
                    var $link = $content.find('a');
                    var domaine = '';
                    var mail = '';
                    // Email et Site Web
                    $link.each(function(){
                        var email = findEmail($(this));
                        if(!email){
                            var url = $(this).attr('href');
                            domaine=url.substring(7);
                            //alert("Ce n'est pas une adresse email : " + url);
                            $('#internet-' + id).text(domaine);
                        }else{
                            //alert("C'est un email : " + email);
                            $('#email-' + id).text(email);
                            mail = email;
                        }
                    });
                    var tel = findPhone($content, id);
                    var $ajaxSave = $.ajax({
                        type: 'post',
                        url : 'save.php',
                        data: '&id=' + id + '&internet=' + encodeURI(domaine) + '&email=' + encodeURI(mail) + '&tel=' + tel
                    });
                    $ajaxSave.done(function(){
                        $obj.text("Extraction Terminée").removeClass('btn-inverse').addClass('btn-success');
                        $time-= 10;
                        $('.all').text(toTime($time) + " restant");
                    });
                });
            }
            /**
             * Récupérer l'email
             * @param {type} $object
             * @returns {Boolean}
             */
            function findEmail($object){
                var href = $object.attr('href');
                var indexOf = href.indexOf('mailto:');
                if(indexOf < 0){
                    return false;
                }else{
                    return href.substring(7);
                }
            }
            
            /**
             * 
             * @param {type} $object
             * @param {type} id
             * @returns {String}
             */
            function findPhone($object, id){
                var text = $object.text();
                var indexOf = text.indexOf('Tél. : ');
                if(indexOf > 0){
                    //alert('Trouvé à la position : ' + indexOf);
                    var continuer = true;
                    var i = indexOf + 7;
                    var tel = '';
                    while(continuer){
                        var nb = text.charAt(i++);
                        if(nb == '.' || nb == ' '){
                            continue;
                        }
                        if(isNaN(nb)){
                            //alert(nb);
                            continuer = false;
                        }else{
                            tel += nb;
                        }
                    }
                    //alert("Tel : " + tel);
                    $('#telephone-' + id).text(tel);
                    return tel;
                }else{
                    //alert('Tel Introuvable');
                    return tel;
                }
            }
            
        </script>
    </body>
</html>
<?php mysql_close($c);